using System.Collections.Generic;
using System.Linq;
using System.Xml.XPath;
using Comdiv.QWeb.Serialization.BxlParser;

namespace Comdiv.QWeb.Bxl {
	public class BxlTree : IXPathNavigable {
		private readonly BxlToken[] _tokens;

		public BxlTree(BxlToken[] tokens) {
			IDictionary<int, BxlToken> lastsforlevel = new Dictionary<int, BxlToken>();
			BxlToken currentElement = null;
			foreach (var t in tokens) {
				BxlToken parent;
				if (BxlTokenType.Element == t.Type) {
					var level = t.Level;
					currentElement = t;
					lastsforlevel[level] = t;
					if (level > 0) {
						parent = lastsforlevel[level - 1];
						parent.Elements.Add(t);
						t.Parent = parent;
					}
				}
				else if (BxlTokenType.Attribute == t.Type || BxlTokenType.Literal == t.Type || BxlTokenType.String == t.Type ||
				         BxlTokenType.Expression == t.Type) {
					parent = t.Level > 0 ? lastsforlevel[t.Level - 1] : currentElement;
					if (parent != null) {
						parent.Attributes.Add(t);
						t.Parent = parent;
					}
				}
				else if (BxlTokenType.Value == t.Type) {
					if (currentElement != null) {
						currentElement.ElementValue = t;
						t.Parent = currentElement;
					}
				}
			}
			_tokens = tokens.Where(x => x.Type == BxlTokenType.Element && x.Level == 0).ToArray();
		}

		public BxlToken[] Tokens {
			get { return _tokens; }
		}

		#region IXPathNavigable Members

		public XPathNavigator CreateNavigator() {
			return new BxlXpathNavigator(this);
		}

		#endregion
	}
}